/** *********************************************************************** */
/*                                                                        */
/* System Name : ICIM */
/*                                                                        */
/* Description : Bis_mtrl Management */
/*                                                                        */
/* MODIFICATION HISTORY */
/* Date Ver Name Description */
/* ---------- ----- ----------- ----------------------------------------- */
/* 2013/05/09 N0.00 Lin.Xin Initial release */
/* 2014/07/09 N0.01 Lin.Xin Recode all */
/*                                                                        */
/** *********************************************************************** */

$(document).ready(function() {

	$("form").submit(function() {
				return false;
			});

	var domObj = {
		$mtrlProdIDTxt : $("#mtrlProdIDTxt"),
		$mtrlProdDscTxt : $("#mtrlProdDscTxt"),
		$mtrlCateSel : $("#mtrlCateSel"),
		$mtrlMkrSel : $("#mtrlMkrSel"),
		//$mtrlChgCateSel : $("#mtrlChgCateSel"),
		//$mtrlUseModeSel : $("#mtrlUseModeSel"),
		$mtrlPrtSel : $("#mtrlPrtSel"),
		grids : {
			$mtrlListGrd : $("#mtrlListGrd"),
			mtrlListGrdSelector : "#$mtrlListGrd",
			$mtrlListDiv : $("#mtrlListDiv"),
			mtrlListPg : "#mtrlListPg",

			$cusListGrd : $("#cusListGrd"),
			cusListGrdSelector : "#cusListGrd",
			cusListPg : "#cusListPg",

			$selectCusDialog_cusListGrd : $("#selectCusDialog_cusListGrd"),
			selectCusDialog_cusListGrdSelector : "#selectCusDialog_cusListGrd",
			selectCusDialog_cusListPg : "#selectCusDialog_cusListPg"
		},
		buttons : {
			$f1QueryBtn : $("#f1_query_btn"),
			$f4DelBtn : $("#f4_del_btn"),
			$f5UpdBtn : $("#f5_upd_btn"),
			$f6AddBtn : $("#f6_add_btn"),
			$f9SaveBtn : $("#f9_save_btn"),
			$f10ClearBtn : $("#f10_clear_btn"),
			$addMtrlMkrBtn : $("#addMtrlMkrBtn"),
			$deleteMtrlMkrBtn : $("#deleteMtrlMkrBtn")
		},
		dialogs : {
			$selectCusDialog : $("#selectCusDialog"),
			$selectCusDialog_selectCusBtn : $("#selectCusDialog_selectCusBtn"),
			$queryMtrlDialog : $("#queryMtrlDialog"),
			$queryMtrlDialog_queryBtn : $("#queryMtrlDialog_queryBtn"),
			$queryMtrlDialog_mtrlProdIDTxt : $("#queryMtrlDialog_mtrlProdIDTxt")
		}

	};
	var VAL = {
		NORMAL : "0000000",
		DISABLED_ATTR : {
			'disabled' : true
		},
		ENABLED_ATTR : {
			'disabled' : false
		},
		T_XPBISMTR : "XPBISMTR",
		ACTION_ADD : "A",
		ACTION_UPDATE : "U"
	};
	var globalObj = {
		cusdOaryAry : {}
	};

	var SelectDom = {

		hasTxt : function($selectDomObj, txt) {

			var $options, optCnt, i;

			$options = $($selectDomObj.selector + " option");
			optCnt = $options.length;

			for (i = 0; i < optCnt; i++) {
				if ($options[i].text === txt) {
					break;
				}
			}

			return i < optCnt ? true : false;
		},
		hasValue : function($selectDomObj, val) {
			return $($selectDomObj.selector + " option[value='" + val + "']").length > 0
					? true
					: false;
		},
		addSelect : function($selectDomObj, val, txt) {
			txt = (typeof(txt) === "undefined" ? val : txt);
			if (val && !this.hasValue(val)) {
				$selectDomObj.append("<option value=" + val + ">" + txt
						+ "</option>");
				$selectDomObj.select2({
				    	theme : "bootstrap"
				    });
			}
		},
		setSelect : function($selectDomObj, val, txt) {
			if (val) {
				// 这样写是不好的,三元运算符仅仅用在条件赋值中,而不要作为if语句的替代品
				// this.hasValue($selectDomObj, val) ? this.val(val) :
				// this.addSelect($selectDomObj, val, txt);
				if (this.hasValue($selectDomObj, val)) {
					$selectDomObj.val(val).trigger("change");;
				} else {
					this.addSelect($selectDomObj, val, txt);
				}
			}
		}
	};
	var CheckBoxDom = {
		setCheckBox : function($domObj, checkFlg) {
			if (checkFlg) {
				$domObj.attr("checked", "true");
			} else {
				$domObj.removeAttr("checked");
			}
		},
		isChecked : function($domObj) {
			return ($domObj.attr("checked") === "checked" ? true : false);
		}
	};

	domObj.grids.$mtrlListGrd.jqGrid({
		url : "",
		datatype : "local",
		mtype : "POST",
		height : domObj.grids.$mtrlListDiv.height(),
		autowidth : true,// 宽度根据父元素自适应
		shrinkToFit : true,
		scroll : false,
		resizable : true,
		loadonce : true,
		fixed : true,
		viewrecords : true, // 显示总记录数
		pager : domObj.grids.mtrlListPg,
		rownumbers : true,// 显示行号
		rowNum : 20, // 每页多少行，用于分页
		rownumWidth : 20, // 行号列宽度
		emptyrecords : true,
		colModel : [{
					name : 'mtrl_prod_id',
					index : 'mtrl_prod_id',
					label : MTRL_PRODUCT_ID_TAG,
					width : 60
				}, {
					name : 'mtrl_prod_dsc',
					index : 'mtrl_prod_dsc',
					label : "原料描述",
					width : 60
				}, {
					name : 'data_seq_id',
					index : 'data_seq_id',
					label : "主键",
					width : 280,
					hidden : true
				}],
		gridComplete : function() {
			var gridPager, pageLen;
			gridPager = $(this).jqGrid("getGridParam", "pager");
			if (gridPager.length < 2) {
				return false;
			}
			$("#sp_1_" + gridPager.substr(1, pageLen - 1)).hide();
			$(".ui-pg-input").hide();
			$('td[dir="ltr"]').hide();
			$(gridPager + "_left").hide();
			$(gridPager + "_center").css({
						width : 0
					});
			$(".ui-pg-button").remove();
		},
		onSelectRow : function(id) {
			var rowData, mtrl_product_id, iary, inObj, outObj, oary, tblCnt, i, j, cusdOary, cusdCnt;

			$("input").attr(VAL.DISABLED_ATTR);
			$("select").attr(VAL.DISABLED_ATTR);

			rowData = $(this).jqGrid("getRowData", id);
			inObj = {
				trx_id : VAL.T_XPBISMTR,
				action_flg : "Q",
				iary : {
					mtrl_prod_id : rowData.mtrl_prod_id
				},
				tbl_cnt : 1
			};
			outObj = comTrxSubSendPostJson(inObj);
			if (outObj.rtn_code !== VAL.NORMAL) {
				return false;
			}
			tblCnt = outObj.tbl_cnt;
			oary = tblCnt > 1 ? outObj.oary[0] : outObj.oary;
			domObj.$mtrlProdIDTxt.val(oary.mtrl_prod_id);
			domObj.$mtrlProdDscTxt.val(oary.mtrl_prod_dsc);
			SelectDom.setSelect(domObj.$mtrlCateSel, oary.mtrl_cate);
			SelectDom.setSelect(domObj.$mtrlMkrSel, oary.mtrl_mkr);
			//SelectDom.setSelect(domObj.$mtrlChgCateSel, oary.mtrl_chg_cate);
			//SelectDom.setSelect(domObj.$mtrlUseModeSel, oary.mtrl_use_mode);
			SelectDom.setSelect(domObj.$mtrlPrtSel, oary.mtrl_part);

			inObj = {
				trx_id : "XPLSTDAT",
				action_flg : "Q",
				iary : {
					data_cate : "CSMT",
					ext_1 : domObj.$mtrlProdIDTxt.val()
				}
			};
			outObj = comTrxSubSendPostJson(inObj);
			if (outObj.rtn_code === VAL.NORMAL) {
				tblCnt = outObj.tbl_cnt;
				cusdCnt = globalObj.cusdOaryAry.length;// TODO此处如果oaryAry不是数组就有问题
				for (i = 0; i < tblCnt; i++) {
					oary = tblCnt > 1 ? outObj.oary[i] : outObj.oary;
					for (j = 0; j < cusdCnt; j++) {
						cusdOary = cusdCnt > 1
								? globalObj.cusdOaryAry[j]
								: globalObj.cusdOaryAry;
						if (oary.data_item === cusdOary.data_item) {
							oary.data_ext = cusdOary.data_ext;
							break;
						}
					}
				}
				setGridInfo(outObj.oary, domObj.grids.$cusListGrd);
			}

		}
	})

	domObj.grids.$cusListGrd.jqGrid({
				url : "",
				datatype : "local",
				mtype : "POST",
				width : 400,
				height : 200,
				// autowidth:true,//宽度根据父元素自适应
				shrinkToFit : true,
				scroll : false,
				resizable : true,
				loadonce : true,
				fixed : true,
				viewrecords : true, // 显示总记录数
				pager : domObj.grids.cusListPg, // '#cusList2Pg',
				rownumbers : true,// 显示行号
				rowNum : 20, // 每页多少行，用于分页
				rownumWidth : 20, // 行号列宽度
				emptyrecords : true,
				pginput : true,// 可以输入跳转页数
				// toolbar : [true, "top"],//显示工具列 : top,buttom,both
				colModel : [{
							name : 'data_item',
							index : 'data_item',
							label : '物料厂商代码',
							width : 120
						}, {
							name : 'data_ext',
							index : 'data_ext',
							label : "物料厂商名称",
							width : 280
						}, {
							name : 'data_seq_id',
							index : 'data_seq_id',
							label : "主键",
							width : 280,
							hidden : true
						}],
				ondblClickRow : function(id) {
				}
			})
	function initFnc() {
		var inObj, outObj, cusIds, oaryAry, oary, tblCnt, i, j;
		$("input").attr(VAL.DISABLED_ATTR);
		$("select").attr(VAL.DISABLED_ATTR);
		$("input").val("");
		$("select").empty();
		domObj.grids.$cusListGrd.jqGrid("clearGridData");
		inObj = {
			trx_id : "XPLSTDAT",
			action_flg : "Q",
			iary : {
				data_cate : "CUSD",
				 list_all_cus_flg:"Y"
			}
		};
		outObj = comTrxSubSendPostJson(inObj);
		if (outObj.rtn_code === VAL.NORMAL) {
			globalObj.cusdOaryAry = outObj.tbl_cnt> 1 ? outObj.oary :[outObj.oary];
		}
	}

	domObj.grids.$selectCusDialog_cusListGrd.jqGrid({
				url : "",
				datatype : "local",
				mtype : "POST",
				width : 360,
				height : 450,
				shrinkToFit : true,
				scroll : false,
				resizable : true,
				loadonce : true,
				fixed : true,
				viewrecords : true, // 显示总记录数
				pager : domObj.grids.selectCusDialog_cusListPg,
				rownumbers : true,// 显示行号
				rowNum : 20, // 每页多少行，用于分页
				rownumWidth : 20, // 行号列宽度
				emptyrecords : true,
				colModel : [{
							name : 'data_item',
							index : 'data_item',
							label : '物料厂商代码',
							width : 90
						}, {
							name : 'data_ext',
							index : 'data_ext',
							label : "物料厂商名称",
							width : 270
						}],
				ondblClickRow : function(id) {
					selectCusFnc();
				}
			});

	function selectCusFnc() {
		var selRowId, rowData, rowIds, newRowId, i, cusRowData;
		var mtrlProdId, inObj, outObj, iary, oary;

		selRowId = domObj.grids.$selectCusDialog_cusListGrd.jqGrid(
				"getGridParam", "selrow");

		mtrlProdId = domObj.$mtrlProdIDTxt.val().trim();
		if (!mtrlProdId) {
			showErrorDialog("请选择要绑定的原料产品代码");
			return false;
		}
		if (!selRowId) {
			showErrorDialog("请选择要绑定的客户");
			return false;
		}

		rowData = domObj.grids.$selectCusDialog_cusListGrd.jqGrid("getRowData",
				selRowId);

		rowIDs = domObj.grids.$cusListGrd.jqGrid("getDataIDs");
		for (i = 0; i < rowIDs.length; i++) {
			cusRowData = domObj.grids.$cusListGrd.jqGrid("getRowData",
					rowIDs[i]);
			if (cusRowData.data_item === rowData.data_item) {
				showErrorDialog("此客户已经绑定过,重复!");
				return false;
			}
		}
		iary = {
			data_cate : "CSMT",
			data_item : rowData.data_item,
			ext_1 : mtrlProdId
		};
		inObj = {
			trx_id : "XPLSTDAT",
			action_flg : "A",
			tbl_cnt : 1,
			iary : iary
		}
		outObj = comTrxSubSendPostJson(inObj);
		if (outObj.rtn_code === VAL.NORMAL) {
			oary = outObj.tbl_cnt > 1 ? outObj.oary[i] : outObj.oary;
			rowData.data_seq_id = oary.data_seq_id;
			newRowId = rowIDs[rowIDs.length - 1] + 1 + "";
			domObj.grids.$cusListGrd.jqGrid("addRowData", newRowId, rowData);
			domObj.grids.$selectCusDialog_cusListGrd.jqGrid("delRowData",selRowId);
			domObj.dialogs.$selectCusDialog.modal("hide");
					
		}

	}
	function initGridData() {
		setGridInfo(globalObj.cusdOaryAry,
				domObj.grids.$selectCusDialog_cusListGrd);
	}
	function showSelectCusDialog() {
		domObj.dialogs.$selectCusDialog.modal({
					backdrop : true,
					keyboard : false,
					show : false
				});
		domObj.dialogs.$selectCusDialog.unbind('shown.bs.modal');
		domObj.dialogs.$selectCusDialog_selectCusBtn.unbind('click');

		domObj.dialogs.$selectCusDialog.modal("show");
		domObj.dialogs.$selectCusDialog_selectCusBtn
				.bind('click', selectCusFnc);
		initGridData();

	}
	function delCusIdFnc() {
		var inObj, outObj, iary, selRowId, rowData;
		selRowId = domObj.grids.$cusListGrd.jqGrid("getGridParam", "selrow");
		rowData = domObj.grids.$cusListGrd.jqGrid("getRowData", selRowId);

		domObj.buttons.$deleteMtrlMkrBtn.showCallBackWarnningDialog({
					errMsg : "是否删除原料客户对应关系,请确认!!!!",
					callbackFn : function(data) {
						if (data.result == true) {
							iary = {
								data_seq_id : rowData.data_seq_id
							};
							inObj = {
								trx_id : "XPLSTDAT",
								action_flg : "D",
								iary : iary,
								tbl_cnt : 1
							};
							outObj = comTrxSubSendPostJson(inObj);
							if (outObj.rtn_code === VAL.NORMAL) {
								showSuccessDialog("删除客户关系成功");
							}
							domObj.grids.$cusListGrd.jqGrid("delRowData",
									selRowId);
						}
					}
				})

	}

	function f1QueryFnc() {

		/** * 将Div实例化为modal窗体 ** */
		function diaLogQueryFnc() {
			var mtrl_prod_id, inObj, outObj, iary;

			mtrl_prod_id = domObj.dialogs.$queryMtrlDialog_mtrlProdIDTxt.val();
			iary = {};

			if (mtrl_prod_id) {
				iary.mtrl_prod_id = mtrl_prod_id
			}
			inObj = {
				trx_id : VAL.T_XPBISMTR,
				action_flg : 'Q',
				iary : iary,
				tbl_cnt : 1
			};
			outObj = comTrxSubSendPostJson(inObj);
			if (outObj.rtn_code === VAL.NORMAL) {
				setGridInfo(outObj.oary, "#mtrlListGrd");
				domObj.dialogs.$queryMtrlDialog.modal("hide");
			}
		}
		function queryMtrlDialogShowFnc() {
			$("#queryMtrlDialog_mtrlForm input").val("");
		}

		domObj.dialogs.$queryMtrlDialog.modal({
					backdrop : true,
					keyboard : false,
					show : false
				});
		domObj.dialogs.$queryMtrlDialog.unbind('shown.bs.modal');
		domObj.dialogs.$queryMtrlDialog_queryBtn.unbind('click');

		domObj.dialogs.$queryMtrlDialog.bind('shown.bs.modal', queryMtrlDialogShowFnc);
		domObj.dialogs.$queryMtrlDialog.modal("show");
		domObj.dialogs.$queryMtrlDialog_queryBtn.bind('click', diaLogQueryFnc);
		// domObj.dialogs.$queryMtrlDialog_mtrlProdIDTxt.attr(VAL.ENABLED_ATTR);
		$("#queryMtrlDialog_mtrlProdIDTxt").attr(VAL.ENABLED_ATTR);

	}

	domObj.buttons.$f1QueryBtn.click(f1QueryFnc);

	initFnc();

	function getAddRowID() {
		var rowIDs = domObj.grids.$mtrlListGrd.jqGrid("getDataIDs");
		return (parseInt(rowIDs[rowIDs.length - 1]) + 1) + "";
	}
	function f9SaveFnc() {
		var inObj, outObj, iary;
		var action_flg, mtrl_prod_id, mtrl_prod_dsc, mtrl_cate;
		action_flg = domObj.buttons.$f9SaveBtn.data("save_flg");
		if (action_flg == undefined) {
			return false;
		}

		mtrl_prod_id = domObj.$mtrlProdIDTxt.val().trim();
		mtrl_prod_dsc = domObj.$mtrlProdDscTxt.val().trim();
		mtrl_cate = domObj.$mtrlCateSel.find("option:selected").text();
		mtrl_mkr = domObj.$mtrlMkrSel.val();
		//mtrl_chg_cate = domObj.$mtrlChgCateSel.find("option:selected").text();
		//mtrl_use_mode = domObj.$mtrlUseModeSel.find("option:selected").text();
		mtrl_part = domObj.$mtrlPrtSel.find("option:selected").text();

		if (!mtrl_prod_id) {
			showErrorDialog("","原料产品代码不能为空,请填写");
			return false;
		}
		if (domObj.grids.$cusListGrd.jqGrid("getDataIDs") <= 0) {
			showErrorDialog("","没有绑定原料和客户关系,错误");
			return false;
		}
		iary = {
			mtrl_prod_id : mtrl_prod_id,
			mtrl_prod_dsc : mtrl_prod_dsc,
			mtrl_cate : mtrl_cate,
			mtrl_mkr : mtrl_mkr,
			mtrl_chg_cate : "",
			mtrl_use_mode : "",
			mtrl_part : mtrl_part
		};
		inObj = {
			trx_id : VAL.T_XPBISMTR,
			action_flg : action_flg,
			iary : iary,
			tbl_cnt : 1
		};
		outObj = comTrxSubSendPostJson(inObj);
		if (outObj.rtn_code === VAL.NORMAL) {
			if (action_flg === "A") {
				showSuccessDialog("新增物料成功");

				domObj.grids.$mtrlListGrd.jqGrid("addRowData", getAddRowID,
						iary);
			} else if (action_flg === "U") {
				showSuccessDialog("物料信息更新成功");
			}
			$("input").attr(VAL.DISABLED_ATTR);
			$("select").attr(VAL.DISABLED_ATTR);
			$("input").val("");
			$("select").empty();
		}
	};

	function f6AddFnc() {
		$("input").attr(VAL.ENABLED_ATTR);
		$("select").attr(VAL.ENABLED_ATTR);
		$("input").val("");
		$("select").empty();
		domObj.grids.$cusListGrd.jqGrid("clearGridData");
		$("checkbox").removeAttr("checked");
		//addValueByDataCateFnc("#mtrlChgCateSel", "MTCC", "data_id");
		//addValueByDataCateFnc("#mtrlUseModeSel", "MTUM", "data_id");
		addValueByDataCateFnc("#mtrlCateSel", "MTCT", "data_id");
		addValueByDataCateFnc("#mtrlPrtSel", "MTPT", "ext_1");
		setSelectObjValueTxtByData("#mtrlMkrSel", "CUSD", "data_item","data_ext");
		domObj.buttons.$f9SaveBtn.data("save_flg", "A");

	}
	function f5UpdateFnc() {
		$("input").attr(VAL.ENABLED_ATTR);
		$("select").attr(VAL.ENABLED_ATTR);
		domObj.$mtrlProdIDTxt.attr(VAL.ENABLED_ATTR);
		//addValueByDataCateFnc("#mtrlChgCateSel", "MTCC", "data_id");
		//addValueByDataCateFnc("#mtrlUseModeSel", "MTUM", "data_id");
		addValueByDataCateFnc("#mtrlCateSel", "MTCT", "data_id");
		addValueByDataCateFnc("#mtrlPrtSel", "MTPT", "ext_1");
		setSelectObjValueTxtByData("#mtrlMkrSel", "CUSD", "data_item",
				"data_ext");
		domObj.buttons.$f9SaveBtn.data("save_flg", "U");
	}
	function f4DelFnc() {
		var inObj, outObj, iary, rowIDs, tblCnt, i,j;
		var rowIDs, rowCnt, i;
		var iaryAry = new Array();
		var mtrl_prod_id = domObj.$mtrlProdIDTxt.val();
		if (!mtrl_prod_id) {
			showErrorDialog("003", "请选择需要删除的原料");
			return false;
		}
		$("#deleteDatacateDialog_deleteDateCateBtn")
				.showCallBackWarnningDialog({
					errMsg : "是否删除原料信息,请确认!!!!",
					callbackFn : function(data) {
						if (data.result == true) {
							iary = {
								mtrl_prod_id : mtrl_prod_id
							};
							inObj = {
								trx_id : 'XPBISMTR',
								action_flg : 'D',
								iary : iary,
								tbl_cnt : 1
							};
							outObj = comTrxSubSendPostJson(inObj);
							if (outObj.rtn_code == VAL.NORMAL) {
								rowIDs = domObj.grids.$mtrlListGrd
										.jqGrid("getDataIDs");
								rowCnt = rowIDs.length;
								for (i = 0; i < rowCnt; i++) {
									rowData = domObj.grids.$mtrlListGrd.jqGrid(
											"getRowData", rowIDs[i]);
									if (mtrl_prod_id == rowData.mtrl_prod_id) {
										domObj.grids.$mtrlListGrd.jqGrid(
												"delRowData", rowIDs[i]);
										break;
									}
								}
							    var cusrowIDs  = $("#cusListGrd").jqGrid("getDataIDs");
							    if(cusrowIDs.length>0){
							    	for( j=0;j<cusrowIDs.length;j++){
									      var cusrowData = $("#cusListGrd").jqGrid("getRowData",cusrowIDs[j]);
                                          var iarycus = {
                                        		  data_seq_id  : cusrowData.data_seq_id
                                          };
                                          iaryAry.push(iarycus);
							    	}
							    	inObj = {
											trx_id : "XPLSTDAT",
											action_flg : "D",
											iary : iaryAry,
											tbl_cnt : 1
										};
										outObj = comTrxSubSendPostJson(inObj);
										if (outObj.rtn_code === VAL.NORMAL) {
											showSuccessDialog("删除原料成功");
											$("#cusListGrd").jqGrid("clearGridData");
										}
							    }
								$("input").attr(VAL.DISABLED_ATTR);
								$("select").attr(VAL.DISABLED_ATTR);
								$("input").val("");
								$("select").empty();

							}

						}
					}
				});
	}
	function f10ClearFnc() {
		$("input").val("");
		$("select").empty();
		$("checkbox").removeAttr("checked");
		domObj.grids.$mtrlListGrd.jqGrid("clearGridData");
		$("input").attr(VAL.DISABLED_ATTR);
		$("select").attr(VAL.DISABLED_ATTR);
	}
	domObj.buttons.$f9SaveBtn.click(f9SaveFnc);
	domObj.buttons.$f4DelBtn.click(f4DelFnc);
	domObj.buttons.$f5UpdBtn.click(f5UpdateFnc);
	domObj.buttons.$f6AddBtn.click(f6AddFnc);
	domObj.buttons.$f10ClearBtn.click(f10ClearFnc);
	domObj.buttons.$addMtrlMkrBtn.click(showSelectCusDialog);
	domObj.buttons.$deleteMtrlMkrBtn.click(delCusIdFnc);
})